package main

import (
	"fmt"
	"sync"
)

var total int
var wg sync.WaitGroup
var lock sync.Mutex

/** 互斥锁:  默认的Lock()就是写锁 */

func add() {
	defer wg.Done()
	for i := 1; i < 1000000; i++ {
		lock.Lock()
		total = total + 1
		lock.Unlock()
	}
}

func sub() {
	defer wg.Done()
	for i := 1; i < 1000000; i++ {
		lock.Lock()
		total = total - 1
		lock.Unlock()
	}
}

func main() {
	wg.Add(2)
	// 因为协程需要竞争cpu资源，抢占调度，会导致add()与sub()对total变量不间断的加减
	// 所以加上互斥锁，对抢占资源时加锁
	go add()
	go sub()
	wg.Wait()
	fmt.Println("end:", total) // end: 0
}
